import json

from .serializers import *

from django.db import transaction
from rest_framework.viewsets import ViewSet
from django.db import connection
from .tools import *
from rest_framework.response import Response
from django.db.models import Q


# 采购
class PurchaseView(ViewSet):

    # 新增采购订单
    @transaction.atomic
    def addOrder(self, request):
        # 1. 验证主订单数据
        requestData = request.data
        requestData = setDictNone(requestData)
        # 2. 创建订单（事务操作）
        try:
            with transaction.atomic():
                # 获取主订单数据
                items = requestData['items']
                requestData['purchase_code'] = getOrderCode(7)
                order = setDictNone(requestData)
                # 查询供应商
                supplier = FaKuyouSuppliers.objects.get(supplyer_name=order.get('supplier', None))
                if not supplier:
                    return Result.illegal("供应商不存在")
                order['supplyer_code'] = supplier.supplyer_code
                # 构建采购订单对象
                order = updateOrderExamineStatus(order, requestData)
                order['purchase_type'] = "1"

                # 构建采购订单详情对象
                order_info_list = []
                all_money_tax_price = 0
                all_number = 0
                all_money = 0
                all_money_tax = 0
                for item in items:
                    # 查询商品
                    good = getGoodsInfoByCodeOrName(item)
                    if not good[0]:
                        return Result.illegal("商品不存在")
                    # 查询库存
                    status, stock_number, store_id = getGoodsStockInfoByCodeOrName(item)
                    if not status:
                        return Result.illegal("库存不存在")

                    goods = good[1]
                    order_info = {
                        "number": item['number'],
                        "purchase_number": item['number'],
                        "unit_price": item['unit_price'],
                        "goods_attr": goods['more_attribute'],
                        "goods_code": goods['goods_code'],
                        "goods_note": goods['note'],
                        "default_unit": goods['unit_id'],
                        "remark": "",
                        "delivery_time": requestData['delivery_time'],
                        "supplyer_code": supplier.supplyer_code,
                        "preparation_id": requestData['user_id'],
                        "operation_id": requestData['user_id'],
                        "stores_id": store_id,
                        "allow_stock": stock_number
                    }
                    # 计算单位
                    unit_list = FaKuyouUnit.objects.filter(name=item.get('goods_unit_name'))
                    is_default = 0
                    # 单一单位查找
                    for unit in unit_list:
                        if unit.id == order_info['default_unit'] and unit.is_main == "1":
                            order_info['goods_unit'] = unit.id
                            order_info['basic_nmber'] = item.get('number')
                            is_default = 1
                            break
                    # 多单位查找
                    if is_default == 0:
                        for unit in unit_list:
                            if unit.type == "2":
                                unit_con = FaKuyouUnitConversion.objects.filter(vice_unit=unit.id).first()
                                if unit_con.main_unit == order_info['default_unit']:
                                    order_info['goods_unit'] = unit.id
                                    order_info['basic_nmber'] = unit_con.advance_rate * item.get('number')
                                    is_default = 1
                                    break

                    if is_default == 0:
                        return Result.illegal("单位不存在")

                    # 原始金额
                    money = order_info['purchase_number'] * item.get('unit_price')
                    # 计算折扣额
                    discount = item.get('discount', 0)
                    order_info['discount'] = discount
                    order_info['dis_money'] = money * discount / 100
                    order_info['all_money'] = money - order_info['dis_money']
                    # 计算税额
                    tax_rate = item.get('tax_rate', 0)
                    order_info['tax_money'] = round(order_info['all_money'] * (tax_rate / 100), 0)
                    order_info['tax_included'] = round(order_info['unit_price'] * (1 + (tax_rate / 100)), 2)
                    order_info['tax_rate'] = tax_rate

                    # 计算价税合计
                    order_info['money_tax_price'] = round(order_info['tax_money'] + order_info['all_money'], 1)
                    # 查询商品库存
                    stores = FaKuyouGoodsStock.objects.filter(
                        Q(goods_id=good[1]['id']) & Q(stores_id=good[1]['manager_warehouse_id'])).first()
                    if not stores:
                        order_info['allow_stock'] = 0
                    else:
                        order_info['allow_stock'] = stores.stock
                    # 构建采购详情单对象
                    order_info['purchase_code'] = order['purchase_code']
                    # 计算价税合计总和
                    all_money_tax_price += order_info['money_tax_price']
                    all_number += order_info['purchase_number']
                    all_money += order_info['all_money']
                    all_money_tax += order_info['tax_money']
                    order_info_list.append(order_info)
                # 计算总额
                preferential_rate = requestData.get('preferential_rate', 0)
                preferential_money = round(all_money_tax_price * preferential_rate / 100, 1)
                real_money = all_money_tax_price - preferential_money

                # 保存采购订单
                order['preferential_money'] = preferential_money
                order['real_money'] = real_money
                order['number'] = all_number
                order['all_money'] = all_money
                order['tax_money'] = all_money_tax
                order['all_money_tax_price'] = all_money_tax_price
                order_serializer = FaKuyouGoodsPurchaseOrderSerializer(data=order)
                order_serializer.is_valid(raise_exception=True)
                order_serializer.save()

                # 保存采购订单详情单
                for order_info in order_info_list:
                    order_info['preferential_money'] = preferential_money
                    order_info['real_money'] = real_money
                    order_info['library_money'] = real_money
                    order_info['preferential_rate'] = preferential_rate
                    order_info_serializer = FaKuyouGoodsPurchaseOrderInfoSerializer(data=order_info)
                    order_info_serializer.is_valid(raise_exception=True)
                    order_info_serializer.save()

                return Result.success("新增采购订单成功",
                                      {"采购订单": order_serializer.data, "采购订单详情": order_info_list})
        except Exception as e:
            return Result.error("采购订单创建失败", str(e))

    # 新增采购单
    @transaction.atomic()
    def addPurchase(self, request):
        try:
            # 根据订单号获取订单
            purchase_code = request.data['purchase_code']
            requestData = setDictNone(request.data)
            purchase_order = FaKuyouGoodsPurchaseOrder.objects.get(purchase_code=purchase_code)
            order_serializer = FaKuyouGoodsPurchaseOrderSerializer(purchase_order)
            if order_serializer.data['examine_status'] != "1":
                return Result.illegal("订单未审核")
            if FaKuyouGoodsPurOrd.objects.filter(order_id=order_serializer.data['id']).exists():
                return Result.illegal("订单已存在")
            with transaction.atomic():

                # 构建购货单对象
                purchase = order_serializer.data
                purchase['purchase_code'] = getOrderCode(8)
                purchase = updateOrderExamineStatus(purchase, requestData)

                # 添加账户和付款信息等
                account = FaKuyouAccounts.objects.filter(account_name=requestData.get('account')).first()
                if not account:
                    return Result.illegal("账户不存在")
                purchase['account'] = account.id
                purchase['pay_money'] = requestData.get('pay_money', 0)

                # 采购费用构建（cost_data）
                if not requestData.get('cost_data'):
                    purchase['cost_data'] = ""
                    purchase['purchase_money'] = 0
                purchase['cost_data'], purchase['purchase_money'] = getDataCost(requestData.get('cost_data'))
                if not purchase['cost_data']:
                    return Result.illegal(purchase['purchase_money'])

                # 保存购货单
                purchase_serializer = FaKuyouGoodsPurchaseSerializer(data=purchase)
                if not purchase_serializer.is_valid(raise_exception=True):
                    return Result.error("采购单数据验证失败", purchase_serializer.errors)
                purchase_serializer.save()

                # 生成关联表
                purOrd_serializer = FaKuyouGoodsPurOrdSerializer(
                    data={"order_id": order_serializer.data['id'], "purchase_id": purchase_serializer.data['id']})
                purOrd_serializer.is_valid(raise_exception=True)
                purOrd_serializer.save()

                # 获取订单详情
                purchase_order_info = FaKuyouGoodsPurchaseOrderInfo.objects.filter(purchase_code=purchase_code)
                order_info_serializer_list = FaKuyouGoodsPurchaseOrderInfoSerializer(purchase_order_info, many=True)
                # 构建详情单
                order_info_list = []
                for order_info_serializer in order_info_serializer_list.data:

                    # 构建采购单详情对象
                    purchase_info = order_info_serializer
                    purchase_info['purchase_code'] = purchase['purchase_code']
                    purchase_info['order_info_id'] = order_info_serializer['id']
                    purchase_info['preferential_money'] = purchase['preferential_money']
                    purchase_info['real_money'] = purchase['real_money']

                    # 设置批次信息
                    for item in requestData.get('items', []):
                        status, goods = getGoodsInfoByCodeOrName(item)
                        if not status:
                            return Result.illegal(goods)
                        if goods['goods_code'] == order_info_serializer['goods_code']:
                            purchase_info['manufacture'] = item.get('manufacture', 0)
                            purchase_info['batch_name'] = item.get('batch_name', 0)
                            purchase_info['remark'] = item.get('remark', "")
                            purchase_info['guarantee'] = goods['shelf_life']

                    # 保存采购单详情
                    purchase_info_serializer = FaKuyouGoodsPurchaseInfoSerializer(data=purchase_info)
                    purchase_info_serializer.is_valid(raise_exception=True)
                    purchase_info_serializer.save()
                    order_info_list.append(purchase_info_serializer.data)

                    # 详情单关联
                    data = {"order_id": order_info_serializer['id'],
                            "purchase_id": purchase_info_serializer.data['id']}
                    data.update(purchase_info_serializer.data)
                    purOrd_serializer = FaKuyouGoodsPurOrdInfoSerializer(data=data)
                    purOrd_serializer.is_valid(raise_exception=True)
                    purOrd_serializer.save()

            # 生成采购详情单和采购订单详情关联数据
            return Result.success("采购单创建成功", {"采购单": purchase_serializer.data, "采购单详情": order_info_list})
        except Exception as e:
            return Result.error("采购单创建失败", str(e))

    # 新增退货单
    @transaction.atomic()
    def addExchange(self, request):
        try:
            with transaction.atomic():
                # 根据订单号获取订单
                purchase_code = request.data['purchase_code']
                requestDate = setDictNone(request.data)
                purchase = FaKuyouGoodsPurchase.objects.get(purchase_code=purchase_code)
                purchase_serializer = FaKuyouGoodsPurchaseSerializer(instance=purchase)
                if purchase_serializer.data['examine_status'] != "1":
                    return Result.refuse("订单未审核")

                # 判断是否已生成单据
                if FaKuyouGoodsExchange.objects.filter(purchase_id=purchase_serializer.data['purchase_code']).exists():
                    return Result.refuse("订单已存在")

                # 获取购货订单编号
                purOrd = FaKuyouGoodsPurOrd.objects.get(purchase_id=purchase_serializer.data['id'])
                purOrd_serializer = FaKuyouGoodsPurOrdSerializer(instance=purOrd)
                purchaseOrder = FaKuyouGoodsPurchaseOrder.objects.get(id=purOrd_serializer.data['order_id'])
                purchaseOrder_serializer = FaKuyouGoodsPurchaseOrderSerializer(instance=purchaseOrder)
                purchase_order_code = purchaseOrder_serializer.data['purchase_code']

                # 构建退货单对象
                ex_purchase = purchase_serializer.data
                ex_purchase['purchase_code'] = getOrderCode(9)
                ex_purchase = updateOrderExamineStatus(ex_purchase, request.data)
                ex_purchase['purchase_type'] = '2'
                ex_purchase['purchase_id'] = purchase_serializer.data['purchase_code']
                ex_purchase['purchase_order_id'] = purchase_order_code
                account = FaKuyouAccounts.objects.filter(account_name=requestDate.get('account', None)).first()
                if not account:
                    return Result.illegal("账户不存在")
                ex_purchase['account'] = account.id

                # 获取购货单详情
                purchase_info_list = FaKuyouGoodsPurchaseInfo.objects.filter(
                    purchase_code=requestDate.get('purchase_code', None))
                purchase_info_serializer_list = FaKuyouGoodsPurchaseInfoSerializer(purchase_info_list, many=True)

                # 计算总优惠额以及实际金额
                preferential_money = 0
                real_money = 0
                all_number = 0
                all_tax_money = 0
                all_money = 0
                for pur_info_ser in purchase_info_serializer_list.data:
                    for item in requestDate.get('items', []):
                        status, goods = getGoodsInfoByCodeOrName(item)
                        if not status:
                            return Result.illegal(goods)
                        if pur_info_ser.get('goods_code') == goods.get('goods_code') or pur_info_ser.get(
                                'goods_name') == goods.get('goods_name'):
                            pur_info_ser['retreat_number'] = float(item.get('retreat_number', 0))
                            unit_price = float(pur_info_ser.get('unit_price'))
                            retreat_number = float(item.get('retreat_number', 0))
                            tax_rate = float(pur_info_ser.get('tax_rate'))
                            discount = float(decimal.Decimal(pur_info_ser.get('discount')))

                            pur_info_ser['tax_included'] = round(unit_price * (1 + tax_rate / 100), 1)
                            pur_info_ser['dis_money'] = round(unit_price * retreat_number * discount / 100, 1)
                            pur_info_ser['all_money'] = round(unit_price * retreat_number - pur_info_ser['dis_money'],
                                                              1)
                            pur_info_ser['tax_money'] = round(pur_info_ser['all_money'] * tax_rate / 100, 1)
                            pur_info_ser['money_tax_price'] = round(
                                pur_info_ser['all_money'] + pur_info_ser['tax_money'], 1)

                            preferential_money += round(
                                pur_info_ser['money_tax_price'] * (ex_purchase['preferential_rate'] / 100), 2)
                            real_money += round(pur_info_ser['money_tax_price'] - pur_info_ser['money_tax_price'] * (
                                    ex_purchase['preferential_rate'] / 100), 1)
                            all_number += retreat_number
                            all_tax_money += pur_info_ser['tax_money']
                            all_money += pur_info_ser['all_money']
                            break
                # 保存退货单
                ex_purchase['retreat_money'] = requestDate.get('retreat_money', 0)
                ex_purchase['preferential_money'] = preferential_money
                ex_purchase['real_money'] = real_money
                ex_purchase['retreat_number'] = all_number
                ex_purchase['tax_money'] = all_tax_money
                ex_purchase['all_money'] = all_money
                ex_purchase_serializer = FaKuyouGoodsExchangeSerializer(data=ex_purchase)
                ex_purchase_serializer.is_valid(raise_exception=True)
                ex_purchase_serializer.save()

                # 创建退货关联单
                data = {'exchange_id': ex_purchase_serializer.data['id'],
                        'purchase_id': purchase_serializer.data['id'], 'type': 2}
                excpur = FaKuyouGoodsExcpurSerializer(data=data)
                excpur.is_valid(raise_exception=True)
                excpur.save()

                # 构建退货单详情单对象
                ex_purchase_info_list = []
                for purchase_info_serializer in purchase_info_serializer_list.data:
                    purchase_info_serializer = updateOrderExamineStatus(purchase_info_serializer, requestDate)
                    ex_purchase_info = purchase_info_serializer
                    ex_purchase_info['purchase_type'] = 2
                    ex_purchase_info['purchase_code'] = ex_purchase['purchase_code']
                    ex_purchase_info['purchase_info_id'] = purchase_info_serializer['id']
                    ex_purchase_info['purchase_id'] = purchase_info_serializer['purchase_code']
                    ex_purchase_info['preferential_money'] = preferential_money
                    ex_purchase_info['real_money'] = real_money
                    ex_purchase_info['basic_nmber'] = float(purchase_info_serializer['basic_nmber']) / \
                                                      float(purchase_info_serializer['number']) * \
                                                      purchase_info_serializer[
                                                          'retreat_number']
                    # 更新商品库存信息
                    status, stock, stroe_id = getGoodsStockInfoByCodeOrName({'store': ex_purchase_info['stores_id'],
                                                                             'goods_code': ex_purchase_info[
                                                                                 'goods_code']})
                    if not status:
                        return Result.illegal(stock)
                    ex_purchase_info['stores_id'] = stroe_id
                    ex_purchase_info['allow_stock'] = stock
                    ex_purchase_info_serializer = FaKuyouGoodsExchangeInfoSerializer(data=ex_purchase_info)
                    ex_purchase_info_serializer.is_valid(raise_exception=True)
                    ex_purchase_info_serializer.save()

                    # 创建退货关联详情单
                    data['exchange_id'] = ex_purchase_info_serializer.data['id']
                    data['purchase_id'] = purchase_info_serializer['id']
                    data['number'] = ex_purchase_info_serializer.data['retreat_number']
                    data['all_money'] = ex_purchase_info_serializer.data['all_money']
                    data['money_tax_price'] = ex_purchase_info_serializer.data['money_tax_price']
                    data['money'] = requestDate.get('retreat_money', 0)
                    data['tax_money'] = ex_purchase_info_serializer.data['tax_money']
                    data['tax_money'] = ex_purchase_info_serializer.data['tax_money']
                    excpur_info = FaKuyouGoodsExcpurInfoSerializer(data=data)
                    excpur_info.is_valid(raise_exception=True)
                    excpur_info.save()
                    ex_purchase_info_list.append(ex_purchase_info_serializer.data)
                return Result.success("新增退货单成功",
                                      {"退货单": ex_purchase_serializer.data, "退货详情单": ex_purchase_info_list})
        except Exception as e:
            return Result.error("退货单创建失败", str(e))


# 销售
class SalesView(ViewSet):
    # 新增销售订单
    @transaction.atomic()
    def addOrder(self, request):
        # 1. 验证主订单数据
        requestData = request.data
        requestData = setDictNone(requestData)
        # 2. 创建订单（事务操作）
        try:
            with transaction.atomic():
                # 获取主订单数据
                items = requestData['items']
                requestData['purchase_code'] = getOrderCode(10)
                order = setDictNone(requestData)
                # 查询供应商
                customer = FaKuyouCustomer.objects.filter(customer_name=order.get('customer', None)).first()
                if not customer:
                    return Result.illegal("供应商不存在")
                # 查询职员
                staff = FaKuyouStaffMember.objects.get(name=order.get('staff', None))
                if not staff:
                    return Result.illegal("职员不存在")
                order["sale_user"] = staff.id
                if requestData.get("receiving_address", None):
                    order['receiving_address'] = requestData.get("receiving_address", None)
                else:
                    order['receiving_address'] = customer.getgoods_address
                order['customers_id'] = customer.id
                # 构建采购订单对象
                order = updateOrderExamineStatus(order, requestData)
                order['purchase_type'] = "1"

                # 构建采购订单详情对象
                order_info_list = []
                all_money_tax_price = 0
                all_number = 0
                all_money = 0
                all_money_tax = 0
                for item in items:
                    # 查询商品
                    good = getGoodsInfoByCodeOrName(item)
                    if not good[0]:
                        return Result.illegal("商品不存在")
                    # 查询库存
                    status, stock_number, store_id = getGoodsStockInfoByCodeOrName(item)
                    if not status:
                        return Result.illegal("库存不存在")

                    goods = good[1]
                    order_info = {
                        "number": item['number'],
                        "purchase_number": item['number'],
                        "unit_price": item['unit_price'],
                        "goods_attr": goods['more_attribute'],
                        "goods_code": goods['goods_code'],
                        "goods_note": goods['note'],
                        "default_unit": goods['unit_id'],
                        "remark": "",
                        "delivery_time": requestData['delivery_time'],
                        "customers_id": customer.id,
                        "stores_id": store_id,
                        "allow_stock": stock_number,
                        **order
                    }
                    # 计算单位
                    unit_list = FaKuyouUnit.objects.filter(name=item.get('goods_unit_name'))
                    is_default = 0
                    # 单一单位查找
                    for unit in unit_list:
                        if unit.id == order_info['default_unit'] and unit.is_main == "1":
                            order_info['goods_unit'] = unit.id
                            order_info['basic_nmber'] = item.get('number')
                            is_default = 1
                            break
                    # 多单位查找
                    if is_default == 0:
                        for unit in unit_list:
                            if unit.type == "2":
                                unit_con = FaKuyouUnitConversion.objects.filter(vice_unit=unit.id).first()
                                if unit_con.main_unit == order_info['default_unit']:
                                    order_info['goods_unit'] = unit.id
                                    order_info['basic_nmber'] = unit_con.advance_rate * item.get('number')
                                    is_default = 1
                                    break

                    if is_default == 0:
                        return Result.illegal("单位不存在")

                    # 原始金额
                    money = order_info['purchase_number'] * item.get('unit_price')
                    # 计算折扣额
                    discount = item.get('discount', 0)
                    order_info['discount'] = discount
                    order_info['dis_money'] = money * discount / 100
                    order_info['all_money'] = money - order_info['dis_money']
                    order_info['library_money'] = order_info['all_money']
                    # 计算税额
                    tax_rate = item.get('tax_rate', 0)
                    order_info['tax_money'] = round(order_info['all_money'] * (tax_rate / 100), 0)
                    order_info['tax_included'] = round(order_info['unit_price'] * (1 + (tax_rate / 100)), 2)
                    order_info['tax_rate'] = tax_rate

                    # 计算价税合计
                    order_info['money_tax_price'] = round(order_info['tax_money'] + order_info['all_money'], 1)
                    # 查询商品库存
                    stores = FaKuyouGoodsStock.objects.filter(
                        Q(goods_id=good[1]['id']) & Q(stores_id=good[1]['manager_warehouse_id'])).first()
                    if not stores:
                        order_info['allow_stock'] = 0
                    else:
                        order_info['allow_stock'] = stores.stock
                    # 构建采购详情单对象
                    order_info['purchase_code'] = order['purchase_code']
                    # 计算价税合计总和
                    all_money_tax_price += order_info['money_tax_price']
                    all_number += order_info['purchase_number']
                    all_money += order_info['all_money']
                    all_money_tax += order_info['tax_money']
                    order_info_list.append(order_info)
                # 计算总额
                preferential_rate = requestData.get('preferential_rate', 0)
                preferential_money = round(all_money_tax_price * preferential_rate / 100, 1)
                real_money = all_money_tax_price - preferential_money

                # 保存采购订单
                order['preferential_money'] = preferential_money
                order['real_money'] = real_money
                order['number'] = all_number
                order['all_money'] = all_money
                order['tax_money'] = all_money_tax
                order['money_tax_price'] = all_money_tax_price
                order_serializer = FaKuyouGoodsSalesOrderSerializer(data=order)
                order_serializer.is_valid(raise_exception=True)
                order_serializer.save()

                # 保存采购订单详情单
                for order_info in order_info_list:
                    order_info['preferential_money'] = preferential_money
                    order_info['real_money'] = real_money
                    order_info['preferential_rate'] = preferential_rate
                    order_info_serializer = FaKuyouGoodsSalesOrderInfoSerializer(data=order_info)
                    order_info_serializer.is_valid(raise_exception=True)
                    order_info_serializer.save()

                return Result.success("新增销售订单成功",
                                      {"销售订单": order_serializer.data, "销售订单详情": order_info_list})
        except Exception as e:
            return Result.error("销售订单创建失败", str(e))

    # 新增销售单
    @transaction.atomic()
    def addSales(self, request):
        try:
            # 根据订单号获取订单
            purchase_code = request.data['purchase_code']
            requestData = setDictNone(request.data)
            sale_order = FaKuyouGoodsSalesOrder.objects.filter(purchase_code=purchase_code).first()
            if not sale_order:
                return Result.illegal("订单不存在")
            order_serializer = FaKuyouGoodsSalesOrderSerializer(sale_order)
            if order_serializer.data['examine_status'] != "1":
                return Result.illegal("订单未审核")
            if FaKuyouGoodsSaleord.objects.filter(order_id=order_serializer.data['id']).exists():
                return Result.illegal("订单已存在")
            with transaction.atomic():

                # 构建购货单对象
                purchase = order_serializer.data
                purchase['purchase_code'] = getOrderCode(11)
                purchase['purchase_order_id'] = sale_order.purchase_code
                purchase['customers_money'] = requestData.get('customer_money', 0)
                purchase = updateOrderExamineStatus(purchase, requestData)

                # 添加账户和付款信息等
                account = FaKuyouAccounts.objects.filter(account_name=requestData.get('account')).first()
                if not account:
                    return Result.illegal("账户不存在")
                purchase['account'] = account.id
                purchase['pay_money'] = requestData.get('pay_money', 0)

                # 采购费用构建（cost_data）
                if not requestData.get('cost_data'):
                    purchase['cost_data'] = ""
                    purchase['purchase_money'] = 0
                purchase['cost_data'], purchase['purchase_money'] = getDataCost(requestData.get('cost_data'))
                if not purchase['cost_data']:
                    return Result.illegal(purchase['purchase_money'])

                # 保存购货单
                purchase_serializer = FaKuyouGoodsSalesSerializer(data=purchase)
                if not purchase_serializer.is_valid(raise_exception=True):
                    return Result.error("采购单数据验证失败", purchase_serializer.errors)
                purchase_serializer.save()

                # 生成关联表
                purOrd_serializer = FaKuyouGoodsSaleordSerializer(
                    data={"order_id": order_serializer.data['id'], "purchase_id": purchase_serializer.data['id']})
                purOrd_serializer.is_valid(raise_exception=True)
                purOrd_serializer.save()

                # 获取订单详情
                purchase_order_info = FaKuyouGoodsSalesOrderInfo.objects.filter(purchase_code=purchase_code)
                order_info_serializer_list = FaKuyouGoodsSalesOrderInfoSerializer(purchase_order_info, many=True)

                # 设置批次信息
                for item in requestData.get('items', []):
                    status, goods = getGoodsInfoByCodeOrName(item)
                    if not status:
                        return Result.illegal("商品不存在")
                    goods_batch_list = FaKuyouGoodsBatch.objects.filter(
                        Q(goods_id=goods['id']) & Q(batch_name=item.get('batch_name', None)))
                    if not goods_batch_list:
                        return Result.illegal("批次不存在")
                    goods_stock_batch_list = FaKuyouGoodsBatchStock.objects.filter(
                        Q(id__in=goods_batch_list.values_list('id', flat=True)) & Q(stock__gt=0))
                    if not goods_stock_batch_list:
                        return Result.illegal("该批次的商品以售卖完毕")
                    if len(goods_stock_batch_list) > 1:
                        return Result.illegal("批次存在多个,请选择。")
                    for order_info_serializer in order_info_serializer_list.data:
                        if order_info_serializer['goods_code'] == goods['goods_code']:
                            order_info_serializer['batch_id'] = goods_stock_batch_list[0].id
                            for goods_batch in goods_batch_list:
                                if goods_batch.id == goods_stock_batch_list[0].id:
                                    order_info_serializer['batch_name'] = goods_batch.batch_name
                                    order_info_serializer['manufacture'] = goods_batch.manufacture
                                    order_info_serializer['guarantee'] = goods_batch.guarantee
                                    order_info_serializer['validity'] = goods_batch.validity
                                    break
                            break

                # 构建详情单
                order_info_list = []
                for order_info_serializer in order_info_serializer_list.data:
                    # 构建采购单详情对象
                    purchase_info = order_info_serializer
                    purchase_info['purchase_code'] = purchase['purchase_code']
                    purchase_info['purchase_order_id'] = purchase_code
                    purchase_info['order_info_id'] = order_info_serializer['id']
                    purchase_info['preferential_money'] = purchase['preferential_money']
                    purchase_info['real_money'] = purchase['real_money']

                    # 保存采购单详情
                    purchase_info_serializer = FaKuyouGoodsSalesInfoSerializer(data=purchase_info)
                    purchase_info_serializer.is_valid(raise_exception=True)
                    purchase_info_serializer.save()
                    order_info_list.append(purchase_info_serializer.data)

                    # 详情单关联
                    data = {"order_id": order_info_serializer['id'],
                            "purchase_id": purchase_info_serializer.data['id']}
                    data.update(purchase_info_serializer.data)
                    purOrd_serializer = FaKuyouGoodsPurOrdInfoSerializer(data=data)
                    purOrd_serializer.is_valid(raise_exception=True)
                    purOrd_serializer.save()

                    # 商品销售批次详情
                    data = order_info_serializer
                    data['purchase_info_id'] = purchase_info_serializer.data['id']
                    data['stock'] = purchase_info_serializer.data['number']
                    data['type'] = "2"
                    goods_batch_info_serializer = GoodsBatchSaleInfoSerializer(data=data)
                    goods_batch_info_serializer.is_valid(raise_exception=True)
                    goods_batch_info_serializer.save()

            # 生成采购详情单和采购订单详情关联数据
            return Result.success("销货单创建成功", {"销货单": purchase_serializer.data, "销货详情单": order_info_list})
        except Exception as e:
            return Result.error("销货单创建失败", str(e))

    # 新增退货单
    @transaction.atomic()
    def addExchange(self, request):
        try:
            # 根据单号查询单据
            with transaction.atomic():
                requestData = setDictNone(request.data)
                purchase_code = requestData['purchase_code']
                sales = FaKuyouGoodsSales.objects.get(purchase_code=purchase_code)
                sales_serializer = FaKuyouGoodsSalesSerializer(instance=sales)
                # 获取销售订单编号
                salesOrd = FaKuyouGoodsSaleord.objects.get(purchase_id=sales_serializer.data['id'])
                sales_order = FaKuyouGoodsSalesOrder.objects.get(id=salesOrd.order_id)
                # 构建退货单对象
                sales_exchange = sales_serializer.data
                sales_exchange['purchase_code'] = getOrderCode(12)
                sales_exchange['purchase_type'] = '2'
                sales_exchange['delivery_time'] = None
                sales_exchange['purchase_order_id'] = sales_order.purchase_code
                sales_exchange['purchase_id'] = sales_serializer.data['purchase_code']
                sales_exchange['retreat_status'] = requestData['retreat_status']
                sales_exchange['retreat_number'] = requestData['retreat_number']
                sales_exchange = updateOrderExamineStatus(sales_exchange, requestData)
                sales_exchange_serializer = FaKuyouGoodsSalesExchangeSerializer(data=sales_exchange)
                sales_exchange_serializer.is_valid(raise_exception=True)
                sales_exchange_serializer.save()

                # 构建退货单详情对象
                sales_info = FaKuyouGoodsSalesInfo.objects.get(purchase_code=purchase_code)
                sales_info_serializer = FaKuyouGoodsSalesInfoSerializer(instance=sales_info)
                sales_exchange_info = sales_info_serializer.data
                sales_exchange_info.update(sales_exchange)
                sales_exchange_info['discount'] = 0
                sales_exchange_info['purchase_info_id'] = sales_info_serializer.data['id']
                ## 获取当前商品库存信息
                stock = FaKuyouGoodsStock.objects.get(goods_code=sales_info_serializer.data['goods_code'],
                                                      stores_id=sales_info_serializer.data['stores_id'])
                sales_exchange_info['allow_stock'] = stock.stock
                sales_exchange_info_serializer = FaKuyouGoodsSalesExchangeInfoSerializer(data=sales_exchange_info)
                sales_exchange_info_serializer.is_valid(raise_exception=True)
                sales_exchange_info_serializer.save()

                # 生成关联单
                data = {'exchange_id': sales_exchange_serializer.data['id'], 'purchase_id': sales_serializer.data['id'],
                        'type': 2}
                sales_saleex_serializer = FaKuyouGoodsSaleExcSerializer(data=data)
                sales_saleex_serializer.is_valid(raise_exception=True)
                sales_saleex_serializer.save()

                # 生成关联详情单
                data = sales_exchange_serializer.data
                data['exchange_id'] = sales_exchange_info_serializer.data['id']
                data['purchase_id'] = sales_info_serializer.data['id']
                data['type'] = 2
                sales_saleex_info_serializer = FaKuyouGoodsSaleExcInfoSerializer(data=data)
                sales_saleex_info_serializer.is_valid(raise_exception=True)
                sales_saleex_info_serializer.save()
                return Result.success("新增销货退货单", sales_exchange_info_serializer.data)
        except Exception as e:
            return Result.error(str(e))


# 管理员
class AdminView(ViewSet):
    @transaction.atomic()
    def login(self, request):
        try:
            with transaction.atomic():
                user = request.data
                group, userId = loginAPI(**user)
                if group:
                    print(
                        "\033[0;33;40m===============================询问结束===============================\033[0m\n\n")
                    print("------------------------------当前部门------------------------------\n" + str(group))
                    return Result.success("认证成功", {"group": group, "userId": userId})
                return Result.illegal("认证失败,请重新输入用户名和工号。")
        except Exception as e:
            return Result.error("发生未知错误", str(e))

    @transaction.atomic()
    def addLog(self, request):
        try:
            log = request.data
            log['url'] = request.data['tables']
            log['ip'] = request.META.get('REMOTE_ADDR')
            log['useragent'] = request.META.get('HTTP_USER_AGENT', 'Unknown')
            print(log)
            log_serializers = FaAdminLogSerializer(data=log)
            log_serializers.is_valid(raise_exception=True)
            log_serializers.save()
            return Result.success("日志记录成功", None)
        except Exception as e:
            return Result.error("日志记录失败", str(e))


# BOM清单
class BOMView(ViewSet):
    # 新增bom清单
    @transaction.atomic()
    def addBom(self, request):
        try:
            with transaction.atomic():
                # 构建bom对象
                bom = request.data
                good = getGoodsInfoByCodeOrName(bom)
                if not good[0]:
                    Result.illegal(good[1])
                bom['goods_code'] = good[1]['goods_code']
                bom['goods_name'] = good[1]['goods_name']
                bom['purchase_code'] = getOrderCode(29)
                bom_serializer = FaKuyouBomSerializer(data=bom)
                bom_serializer.is_valid(raise_exception=True)
                bom_serializer.save()
                return Result.success("新增BOM清单成功", bom_serializer.data)
        except Exception as e:
            return Result.error(str(e))

    # 新增生产工序
    @transaction.atomic()
    def addProcedure(self, request):
        # TODO 未解决问题：一道工序添加多个商品。
        try:
            with transaction.atomic():
                # 构建bom对象
                process = request.data
                good = getGoodsInfoByCodeOrName(process)
                if not good[0]:
                    Result.illegal(good[1])
                process.update(good[1])
                process['purchase_code'] = getOrderCode(30)
                # 获取bom id
                bom = FaKuyouBom.objects.filter(name=process['bom']).first()
                if not bom:
                    return Result.illegal("bom清单不存在")
                process['bom_id'] = bom.id
                # 获取车间 id
                workshop = FaKuyouWorkshop.objects.get(name=process['workshop'])
                process['workshop_id'] = workshop.id
                # 新增生产工序
                bom_process_serializer = FaKuyouBomProcedureSerializer(data=process)
                bom_process_serializer.is_valid(raise_exception=True)
                bom_process_serializer.save()
                # 新增工序商品信息
                process['procedure_id'] = bom_process_serializer.data['id']
                process['good_id'] = good[1]['id']
                process['default_unit'] = good[1]['unit_id']
                process['basic_nmber'] = process['number']
                bom_info_serializer = FaKuyouBomInfoSerializer(data=process)
                bom_info_serializer.is_valid(raise_exception=True)
                bom_info_serializer.save()
                return Result.success("新增生产工序成功", process)

        except Exception as e:
            return Result.error(str(e))


# 生产
class ProductionView(ViewSet):
    # 新增生产计划单
    @transaction.atomic()
    def addPlan(self, request):
        try:
            with transaction.atomic():
                # 构造生产计划对象
                plan = setDictNone(request.data)
                plan = updateOrderExamineStatus(plan, request.data)
                plan['purchase_code'] = getOrderCode(31)
                # 查询车间
                if plan.get('workshop') is not None:
                    workshop = FaKuyouWorkshop.objects.filter(name=plan['workshop']).first()
                    if not workshop:
                        return Result.illegal("车间不存在")
                    plan['workshop_id'] = workshop.id
                else:
                    plan['workshop_id'] = 0
                plan_serializer = FaKuyouPlanSerializer(data=plan)
                plan_serializer.is_valid(raise_exception=True)
                plan_serializer.save()
                # 生产计划总额和总数量
                plan_all_number = 0
                plan_all_money = 0
                # 构建生产计划详情单
                plan_info_list = []
                for item in request.data['items']:
                    plan_info = {}
                    good = getGoodsInfoByCodeOrName(item)
                    if not good[0]:
                        return Result.illegal(
                            (item['goods_name'] if item['goods_name'] else item['goods_code']) + good[1])
                    plan_info.update(good[1])
                    plan_info['plan_id'] = plan_serializer.data['id']
                    plan_info['goods_id'] = good[1]['id']
                    if item.get('purchases') is not None:
                        plan_info['purchase'] = item['purchases']
                    else:
                        plan_info['purchase'] = good[1]['purchases']
                    plan_info['money'] = float(item['number']) * float(plan_info['purchase'])
                    plan_info['number'] = item['number']
                    plan_info['basic_nmber'] = item['number']
                    plan_info['default_unit'] = good[1]['unit_id']
                    plan_all_money += float(plan_info['money'])
                    plan_all_number += float(plan_info['number'])
                    plan_info_serializer = FaKuyouPlanInfoSerializer(data=plan_info)
                    plan_info_serializer.is_valid(raise_exception=True)
                    plan_info_serializer.save()
                    plan_info_list.append(plan_info_serializer.data)

                plan['all_money'] = plan_all_money
                plan['number'] = plan_all_number
                FaKuyouPlan.objects.filter(id=plan_serializer.data['id']).update(
                    all_money=plan['all_money'], number=plan['number'])
                return Result.success("新增生产计划单成功",
                                      {"生产计划单": plan_serializer.data, "生产计划详情": plan_info_list})
        except Exception as e:
            return Result.error(str(e))

    # MRP计算
    @transaction.atomic()
    def addMRP(self, request):
        try:
            with transaction.atomic():
                # 根据生产计划单生产MRP计算单
                now_time = time.time()
                purchase_code = request.data.get('purchase_code')
                # 判断生产计划是否已审核
                plan = FaKuyouPlan.objects.filter(purchase_code=purchase_code).first()
                if plan.examine_status != "1":
                    return Result.illegal("生产计划单未审核")
                MRP = FaKuyouMrp.objects.filter(purchase_code=purchase_code).first()
                if MRP:
                    return Result.illegal("MRP计算单已存在")
                plan_serializer = FaKuyouPlanSerializer(instance=plan)
                MRP_data = plan_serializer.data
                MRP_data['createtime'] = int(now_time)
                MRP_data['updatetime'] = int(now_time)
                MRP_data['purchase_time'] = str(int(now_time))
                MRP_serializer = FaKuyouMrpSerializer(data=MRP_data)
                MRP_serializer.is_valid(raise_exception=True)
                MRP_serializer.save()
                # 查询对应计划单详情
                plan_infos = FaKuyouPlanInfo.objects.filter(plan_id=plan.id)
                plan_info_serializer = FaKuyouPlanInfoSerializer(instance=plan_infos, many=True)

                # 获取生产计划对应生产的商品信息
                MRP_info_list = []
                for plan_info in plan_info_serializer.data:
                    bom = FaKuyouBom.objects.filter(goods_code=plan_info['goods_code']).first()
                    bom_infos = FaKuyouBomInfo.objects.filter(bom_id=bom.id)
                    bom_infos_serializer = FaKuyouBomInfoSerializer(instance=bom_infos, many=True)
                    MRP_info = {'plan_id': MRP_serializer.data['id']}
                    # 获取商品信息对应的bom原材料
                    for bom_info in bom_infos_serializer.data:
                        # 统计原材料库存信息
                        good_stores = FaKuyouGoodsStock.objects.filter(goods_id=bom_info['goods_id'])
                        good_stores_serializer = FaKuyouGoodsStockSerializer(instance=good_stores, many=True)
                        stores_num = 0
                        # 计算商品库存
                        for i in good_stores_serializer.data:
                            stores_num += float(i['stock'])
                        # 构建MRP_info对象
                        MRP_info.update(bom_info)
                        MRP_info['createtime'] = int(now_time)
                        MRP_info['updatetime'] = int(now_time)
                        MRP_info['stock'] = stores_num
                        # 计算所需原材料数量
                        MRP_info['number'] = float(bom_info['number']) * float(plan_info['number'])
                        MRP_info['basic_nmber'] = MRP_info['number']
                        MRP_info['money'] = MRP_info['number'] * float(MRP_info['purchase'])
                        # 计算采购数量
                        MRP_info['buy_number'] = 0 if MRP_info['stock'] - MRP_info['number'] > 0 else -(
                                MRP_info['stock'] - MRP_info['number'])
                        # 保存MRP对象
                        MRP_info_serializer = FaKuyouMrpInfoSerializer(data=MRP_info)
                        MRP_info_serializer.is_valid(raise_exception=True)
                        MRP_info_serializer.save()
                        MRP_info_list.append(MRP_info_serializer.data)
                return Result.success("MRP计算完成", {"MRP": MRP_data, "MRP_info": MRP_info_list})
        except Exception as e:
            return Result.error(str(e))

    # 生产单
    @transaction.atomic()
    def addProduction(self, request):
        try:
            with transaction.atomic():
                # 根据计划单号查询计划单，计划详情单，mrp计算单，mrp计算详情单
                requestData = setDictNone(request.data)
                plan_code = requestData.get('plan_code')
                work_shop = requestData.get('workshop')
                # 获取生产计划单
                plan = FaKuyouPlan.objects.filter(purchase_code=plan_code).first()
                if not plan:
                    return Result.illegal("计划单不存在")
                # 获取MRP计算单
                MRP = FaKuyouMrp.objects.filter(purchase_code=plan_code).first()
                MRP_serializer = FaKuyouMrpSerializer(instance=MRP)
                if not MRP:
                    return Result.illegal("MRP计算单不存在")

                # 构造生产单
                production = {}
                production.update(MRP_serializer.data)
                production = updateOrderExamineStatus(production, requestData)
                production['purchase_code'] = getOrderCode(32)
                production['plan_code'] = plan_code
                production['work_time'] = requestData.get('work_time')
                production['finish_time'] = requestData.get('finish_time')
                production['delivery_time'] = None
                # 查询生产人id
                if requestData.get('work_name') is not None:
                    member = FaKuyouStaffMember.objects.filter(name=requestData.get('work_name')).first()
                    if member is None:
                        return Result.illegal("人员不存在")
                    production['work_id'] = member.id

                # 查询车间id
                if work_shop is not None:
                    work_shop = FaKuyouWorkshop.objects.filter(name=work_shop).first()
                    production['workshop_id'] = work_shop.id
                    if not work_shop:
                        return Result.illegal("车间不存在")
                production_serializer = FaKuyouProductionSerializer(data=production)
                production_serializer.is_valid(raise_exception=True)
                production_serializer.save()
                # 构建生产详情单对象
                production_info_list = []
                # 获取生产计划详情单
                plan_infos = FaKuyouPlanInfo.objects.filter(plan_id=plan.id)
                plan_info_serializer = FaKuyouPlanInfoSerializer(instance=plan_infos, many=True)
                # 添加商品详情
                for plan_info in plan_info_serializer.data:
                    production_info = plan_info
                    production_info['production_id'] = production_serializer.data['id']
                    production_info['type'] = 2
                    production_info['need_number'] = plan_info['number']
                    production_info['stock_number'] = 0
                    production_info_list.append(production_info)
                    production_info_serializer = FaKuyouProductionInfoSerializer(data=production_info)
                    production_info_serializer.is_valid(raise_exception=True)
                    production_info_serializer.save()

                # 获取MRP计算详情单
                MRP_infos = FaKuyouMrpInfo.objects.filter(plan_id=MRP.id)
                MRP_info_serializer = FaKuyouMrpInfoSerializer(instance=MRP_infos, many=True)
                # 添加原材料详情
                for MRP_info in MRP_info_serializer.data:
                    production_info = MRP_info
                    production_info['production_id'] = production_serializer.data['id']
                    production_info['type'] = 1
                    production_info['stock_number'] = MRP_info['stock']
                    production_info['need_number'] = MRP_info['number']
                    production_info_list.append(production_info)
                    production_info_serializer = FaKuyouProductionInfoSerializer(data=production_info)
                    production_info_serializer.is_valid(raise_exception=True)
                    production_info_serializer.save()

            return Result.success("新增生产单成功",
                                  {"生产单": production_serializer.data, "生产详情": production_info_list})

        except Exception as e:
            return Result.error(str(e))

    # 生成领料单
    @transaction.atomic()
    def addPicking(self, request):
        try:
            with transaction.atomic():
                # 根据生产单号查询生产单，生产详情单
                production_code = request.data.get('production_code')
                production = FaKuyouProduction.objects.filter(purchase_code=production_code).first()

                # 判断生产单是否已审核
                if production.examine_status != "1":
                    return Result.illegal("生产单未审核")
                picking = FaKuyouPicking.objects.filter(production_code=production_code).first()
                if picking:
                    return Result.illegal("领料单已存在")
                production_serializer = FaKuyouProductionSerializer(instance=production)
                if not production:
                    return Result.illegal("生产单不存在")
                # 构建领料单
                pick = {}
                pick.update(production_serializer.data)
                pick['purchase_code'] = getOrderCode(33)
                pick['production_code'] = production_code
                # 查询生产人id
                if request.data.get('work_name') is not None:
                    member = FaKuyouStaffMember.objects.filter(name=request.data.get('work_name')).first()
                    if member is None:
                        return Result.illegal("人员不存在")
                    pick['work_id'] = member.id
                pick = updateOrderExamineStatus(pick, request.data)
                # 保存生产单
                pick_serializer = FaKuyouPickingSerializer(data=pick)
                pick_serializer.is_valid(raise_exception=True)
                pick_serializer.save()
                # 构建领料详情单列表
                pick_info_list = []
                # 获取生产详情单
                production_infos = FaKuyouProductionInfo.objects.filter(Q(production_id=production.id) & Q(type=1))
                production_info_serializer = FaKuyouProductionInfoSerializer(instance=production_infos, many=True)
                goods_all_number = 0
                goods_all_money = 0
                for production_info in production_info_serializer.data:
                    # 构建领料详情单对象
                    pick_info = production_info
                    # 查询商品对应仓库id和库存
                    goods = FaKuyouGoods.objects.filter(id=production_info['goods_id']).first()
                    stock = FaKuyouGoodsStock.objects.filter(
                        Q(stores_id=goods.manager_warehouse_id) & Q(goods_id=goods.id)).first()
                    if stock is not None:
                        pick_info['allow_stock'] = stock.stock
                    else:
                        pick_info['allow_stock'] = 0
                    pick_info['stores_id'] = goods.manager_warehouse_id
                    if goods.attribute_id is not "":
                        pick_info['goods_attr'] = goods.attribute_id
                    else:
                        pick_info['goods_attr'] = 0
                    goods_all_number += production_info['number']
                    goods_all_money += production_info['money']
                    pick_info['production_id'] = pick_serializer.data['id']
                    pick_info['type'] = 2
                    pick_info['need_number'] = production_info['money']
                    pick_info = updateOrderBatchStatus(pick_info, request.data)
                    pick_info_list.append(pick_info)
                    pick_info_serializer = FaKuyouPickingInfoSerializer(data=pick_info)
                    pick_info_serializer.is_valid(raise_exception=True)
                    pick_info_serializer.save()

                # 更新领料单
                FaKuyouPicking.objects.filter(id=pick_serializer.data['id']).update(number=goods_all_number,
                                                                                    all_money=goods_all_money)

                pick_serializer.data['number'] = goods_all_number
                pick_serializer.data['all_money'] = goods_all_money
            return Result.success("新增领料单成功", {"领料单": pick_serializer.data, "领料详情单": pick_info_list})
        except Exception as e:
            return Result.error(str(e))

    # 生成退料单
    @transaction.atomic()
    def addMaterial(self, request):
        try:
            with transaction.atomic():
                # 根据生产单号生成退料单
                requestData = setDictNone(request.data)
                production_code = requestData.get('production_code')

                production = FaKuyouProduction.objects.filter(purchase_code=production_code).first()
                if not production:
                    return Result.illegal("生产单不存在")
                # 判断生产单是否已审核
                if production.examine_status != "1":
                    return Result.illegal("生产单未审核")
                if not production:
                    return Result.illegal("生产单不存在")
                production_serializer = FaKuyouProductionSerializer(instance=production)
                material = production_serializer.data
                material['purchase_code'] = getOrderCode(34)
                material['chase_code'] = production_code
                material['production_code'] = production_code
                if requestData.get('code_type') is "" or requestData.get('code_type') == "加工单":
                    material['code_type'] = 1
                else:
                    material['code_type'] = 2
                if requestData.get('workshop') is not None:
                    work_shop = FaKuyouWorkshop.objects.filter(name=requestData.get('workshop')).first()
                    if not work_shop:
                        return Result.illegal("车间不存在")
                    material['workshop_id'] = work_shop.id
                # 查询生产人id
                if requestData.get('work_name') is not None:
                    member = FaKuyouStaffMember.objects.filter(name=requestData.get('work_name')).first()
                    if member is None:
                        return Result.illegal("人员不存在")
                    material['work_id'] = member.id
                    material = updateOrderExamineStatus(material, requestData)
                material_serializer = FaKuyouMaterialSerializer(data=material)
                material_serializer.is_valid(raise_exception=True)
                material_serializer.save()

                # 构建退料详情单
                material_info_list = []
                # 获取退料商品信息
                production_info = FaKuyouProductionInfo.objects.filter(
                    Q(production_id=production.id) & Q(type=1))
                production_info_serializer = FaKuyouProductionInfoSerializer(instance=production_info, many=True)
                # 获取退料商品信息
                all_number = 0
                all_money = 0
                for item in requestData['items']:
                    good = getGoodsInfoByCodeOrName(item)
                    if not good[0]:
                        return Result.illegal(good[1])
                    for production_info in production_info_serializer.data:
                        # 获取商品信息
                        if production_info['goods_id'] == good[1]['id']:
                            goods = FaKuyouGoods.objects.filter(id=production_info['goods_id']).first()
                            material_info = production_info
                            material_info['production_id'] = material_serializer.data['id']
                            material_info['type'] = 2
                            material_info['number'] = item['number']
                            material_info['basic_nmber'] = item['number']
                            material_info['money'] = float(item['number']) * float(material_info['purchase'])
                            material_info['need_number'] = material_info['money']
                            # 仓库库存数量
                            if requestData.get('stores') is not None:
                                stores = FaKuyouStores.objects.filter(
                                    name__istartswith=requestData.get('stores')).first()
                                if stores is None:
                                    return Result.illegal("仓库不存在")
                                material_info['stores_id'] = stores.id
                            else:
                                material_info['stores_id'] = goods.manager_warehouse_id
                            goods_stores = FaKuyouGoodsStock.objects.filter(
                                Q(goods_id=good[1]['id']) & Q(stores_id=material_info['stores_id'])).first()
                            if goods_stores is not None:
                                material_info['allow_stock'] = goods_stores.stock
                            else:
                                material_info['allow_stock'] = 0
                            if goods.attribute_id is not "":
                                material_info['goods_attr'] = goods.attribute_id
                            else:
                                material_info['goods_attr'] = 0
                            stores = FaKuyouStores.objects.filter(id=material_info['stores_id']).first()
                            material_info['stores_name'] = stores.name
                            # 计算总数以及价格
                            all_number += float(material_info['number'])
                            all_money += float(material_info['money'])
                            material_info_list.append(material_info)
                            material_info_serializer = FaKuyouMaterialInfoSerializer(data=material_info)
                            material_info_serializer.is_valid(raise_exception=True)
                            material_info_serializer.save()
                        FaKuyouMaterial.objects.filter(id=material_serializer.data['id']).update(number=all_number,
                                                                                                 all_money=all_money)
                        material_serializer.data['number'] = all_number
                        material_serializer.data['all_money'] = all_money
            return Result.success("生成退料单成功",
                                  {"退料单": material_serializer.data, "退料详情单": material_info_list})
        except Exception as e:
            return Result.error(str(e))

    # 委外加工单
    @transaction.atomic()
    def addOutSourcing(self, request):
        try:
            with transaction.atomic():
                # 根据生产单号生成委外加工单
                requestData = setDictNone(request.data)
                plan_code = requestData.get('plan_code')
                plan = FaKuyouPlan.objects.filter(purchase_code=plan_code).first()
                if plan is None:
                    return Result.illegal("生产计划不存在")
                # 判断生产单是否已审核
                if plan.examine_status != "1":
                    return Result.illegal("生产计划未审核")
                plan_serializer = FaKuyouPlanSerializer(instance=plan)
                # 构建委外加工单对象
                outsourcing = {}
                outsourcing.update(plan_serializer.data)
                outsourcing['purchase_code'] = getOrderCode(35)
                outsourcing['plan_code'] = plan_code
                outsourcing = updateOrderExamineStatus(outsourcing, requestData)
                outsourcing['work_time'] = requestData['work_time']
                outsourcing['finish_time'] = requestData['finish_time']
                # 查询生产工人id
                worker = FaKuyouStaffMember.objects.filter(name=requestData['work_name']).first()
                if worker is None:
                    return Result.illegal("人员不存在")
                outsourcing['work_id'] = worker.id
                # 查询委外工厂id
                factory = FaKuyouFactory.objects.filter(customer_name=requestData['customers_name']).first()
                if factory is None:
                    return Result.illegal("委外工厂不存在")
                outsourcing['customers_id'] = factory.id
                outsourcing['free_money'] = requestData['free_money']
                outsourcing_serializer = FaKuyouOutsourcingSerializer(data=outsourcing)
                outsourcing_serializer.is_valid(raise_exception=True)
                outsourcing_serializer.save()
                # 构建委外加工详情单
                outsourcing_info_list = []
                all_number = 0
                all_money = 0
                plan_infos = FaKuyouPlanInfo.objects.filter(plan_id=plan.id)
                plan_info_serializer = FaKuyouPlanInfoSerializer(instance=plan_infos, many=True)
                for plan_info in plan_info_serializer.data:
                    bom = FaKuyouBom.objects.filter(goods_code=plan_info['goods_code']).first()
                    bom_infos = FaKuyouBomInfo.objects.filter(bom_id=bom.id)
                    bom_info_serializer = FaKuyouBomInfoSerializer(instance=bom_infos, many=True)
                    for bom_info in bom_info_serializer.data:
                        # 构建委外加工详情单对象
                        outsourcing_info = {}
                        outsourcing_info.update(bom_info)
                        outsourcing_info['production_id'] = outsourcing_serializer.data['id']
                        outsourcing_info['type'] = 2
                        # 计算库存情况
                        goods = FaKuyouGoods.objects.filter(id=bom_info['goods_id']).first()
                        outsourcing_info['goods_attr'] = goods.more_attribute
                        outsourcing_info['stores_id'] = goods.manager_warehouse_id
                        stock = FaKuyouGoodsStock.objects.filter(
                            Q(goods_id=goods.id) & Q(stores_id=goods.manager_warehouse_id)).first()
                        if stock is None:
                            outsourcing_info['allow_stock'] = 0
                        else:
                            outsourcing_info['allow_stock'] = stock.stock
                        # 计算数量，金额
                        outsourcing_info['number'] = float(plan_info['number']) * float(
                            bom_info['number'])
                        outsourcing_info['basic_nmber'] = outsourcing_info['number']
                        outsourcing_info['money'] = float(outsourcing_info['number']) * float(
                            bom_info['purchase'])
                        outsourcing_info['need_number'] = outsourcing_info['money']
                        # 计算总数以及价格
                        all_number += float(outsourcing_info['number'])
                        all_money += float(outsourcing_info['money'])
                        outsourcing_info_list.append(outsourcing_info)
                        outsourcing_info_serializer = FaKuyouOutsourcingInfoSerializer(data=outsourcing_info)
                        outsourcing_info_serializer.is_valid(raise_exception=True)
                        outsourcing_info_serializer.save()
                FaKuyouOutsourcing.objects.filter(id=outsourcing_serializer.data['id']).update(number=all_number,
                                                                                               all_money=all_money)
                outsourcing_serializer.data['number'] = all_number
                outsourcing_serializer.data['all_money'] = all_money
                return Result.success("生成委外加工单成功",
                                      {"委外加工单": outsourcing_serializer.data,
                                       "委外加工详情单": outsourcing_info_list})
        except Exception as e:
            return Result.error(str(e))

    # 验收单
    @transaction.atomic()
    def addAcceptance(self, request):
        try:
            with transaction.atomic():
                # 根据生产单号生成验收单
                requestData = setDictNone(request.data)
                production_code = requestData.get('production_code')
                production = FaKuyouProduction.objects.filter(purchase_code=production_code).first()
                if production is None:
                    return Result.illegal("生产单不存在")
                # 构建验收单对象
                acceptance = {}
                production_serializer = FaKuyouProductionSerializer(instance=production)
                acceptance.update(production_serializer.data)
                acceptance = updateOrderExamineStatus(acceptance, requestData)
                acceptance['purchase_code'] = getOrderCode(36)
                acceptance['production_code'] = production_code
                acceptance['chase_code'] = production_code
                acceptance['work_time'] = None
                acceptance['finish_time'] = None
                if requestData.get('type') is "" or requestData.get('type') == "加工单":
                    acceptance['code_type'] = 1
                else:
                    acceptance['code_type'] = 2
                worker = FaKuyouStaffMember.objects.filter(name=requestData['work_name']).first()
                if worker is None:
                    return Result.illegal("人员不存在")
                acceptance['work_id'] = worker.id
                acceptance_serializer = FaKuyouAcceptanceSerializer(data=acceptance)
                acceptance_serializer.is_valid()
                acceptance_serializer.save()
                # 构建验收单详情对象
                all_finish_number = 0
                all_finish_money = 0
                acceptance_info_list = []
                for item in requestData['items']:
                    good = getGoodsInfoByCodeOrName(item)
                    if not good[0]:
                        return Result.illegal(good[1])
                    production_info = FaKuyouProductionInfo.objects.filter(
                        Q(production_id=production.id) & Q(type=2) & Q(goods_name=good[1]['goods_name']) | Q(
                            goods_code=good[1]['goods_code'])).first()
                    production_info_serializer = FaKuyouProductionInfoSerializer(instance=production_info)

                    acceptance_info = {}
                    acceptance_info.update(production_info_serializer.data)
                    all_finish_number += float(item['number'])
                    acceptance_info['need_number'] = float(production_info_serializer.data['number'])
                    acceptance_info['number'] = float(item['number'])
                    acceptance_info['bad_number'] = acceptance_info['need_number'] - float(item['number'])
                    acceptance_info['basic_nmber'] = item['number']
                    acceptance_info['money'] = float(production_info_serializer.data['purchase']) * float(
                        item['number'])
                    acceptance_info['production_id'] = acceptance_serializer.data['id']
                    acceptance_info['stores_id'] = good[1]['manager_warehouse_id']
                    acceptance_info['goods_attr'] = good[1]['more_attribute']
                    all_finish_money += float(acceptance_info['money'])
                    acceptance_info_serializer = FaKuyouAcceptanceInfoSerializer(data=acceptance_info)
                    acceptance_info_serializer.is_valid(raise_exception=True)
                    acceptance_info_serializer.save()
                    acceptance_info_list.append(acceptance_info_serializer.data)

                FaKuyouAcceptance.objects.filter(id=acceptance_serializer.data['id']).update(
                    finish_number=all_finish_number, all_money=all_finish_money)
                return Result.success("生成验收单成功",
                                      {'验收单': acceptance_serializer.data, '验收详情单': acceptance_info_list})

        except Exception as e:
            return Result.error(str(e))


# 仓储
class WarehouseView(ViewSet):

    # 调拨单
    @transaction.atomic()
    def addAllocation(self, request):
        try:
            with transaction.atomic():
                # 获取请求信息
                requestData = setDictNone(request.data)
                # 构建调拨单对象
                allocation = {}
                allocation['purchase_code'] = getOrderCode(13)
                if requestData.get("purchase_time"):
                    allocation['purchase_time'] = requestData['purchase_time']
                else:
                    allocation['purchase_time'] = int(time.time())
                allocation = updateOrderExamineStatus(allocation, requestData)
                allocation['print_num'] = 0
                allocation['admin_id'] = requestData['user_id']
                allocation_serializer = FaKuyouAllocationSerializer(data=allocation)
                allocation_serializer.is_valid(raise_exception=True)
                allocation_serializer.save()

                # 构建调拨单详情
                allocation_info_list = []
                for item in requestData['items']:
                    goods = getGoodsInfoByCodeOrName(item)
                    if not goods[0]:
                        return Result.illegal(goods[1])
                    goods = goods[1]
                    allocation_info = {"allocation_id": allocation_serializer.data['id'], "goods_id": goods['id'],
                                       "goods_attr": goods['more_attribute'], "goods_unit": goods['unit_id'],
                                       "number": item['number'], "goods_note": goods['note'],
                                       "admin_id": requestData['user_id']}
                    # 判断调出仓库
                    if item.get('stores_out'):
                        store = FaKuyouStores.objects.filter(name__contains=item.get('stores_out')).first()
                        if store is None:
                            return Result.illegal("调出仓库不存在")
                        allocation_info['stores_out'] = store.id
                    else:
                        allocation_info['stores_out'] = goods['manager_warehouse_id']

                    # 判断调入仓库
                    if item.get('stores_enter'):
                        store = FaKuyouStores.objects.filter(name__contains=item['stores_enter']).first()
                        if store is None:
                            return Result.illegal("调入仓库不存在")
                        allocation_info['stores_enter'] = store.id

                    stock = FaKuyouGoodsStock.objects.filter(
                        Q(goods_id=goods['id']) & Q(stores_id=allocation_info['stores_out'])).first()
                    if stock:
                        allocation_info['allow_stock'] = stock.stock
                    else:
                        allocation_info['allow_stock'] = 0
                    allocation_info_serializer = FaKuyouAllocationInfoSerializer(data=allocation_info)
                    allocation_info_serializer.is_valid(raise_exception=True)
                    allocation_info_serializer.save()
                    allocation_info_list.append(allocation_info_serializer.data)

                return Result.success("生成调拨单成功",
                                      {"调拨单": allocation_serializer.data, "调拨详情单": allocation_info_list})

        except Exception as e:
            return Result.error(str(e))

    # 盘点单
    @transaction.atomic()
    def addInventory(self, request):
        try:
            with transaction.atomic():
                # 获取请求信息
                requestData = setDictNone(request.data)
                purchase_time = int(time.time())
                # 构建盘点单对象
                inventory = {}
                inventory['purchase_code'] = getOrderCode(15)
                inventory['purchase_time'] = purchase_time
                inventory['store_type'] = 2
                inventory['admin_id'] = requestData['user_id']
                # 查询仓库
                store = FaKuyouStores.objects.filter(name=requestData['store']).first()
                # 查询仓库中商品数量
                check_profit = 0
                check_loss = 0
                inventory_info_list = []
                for item in requestData['items']:
                    goods = getGoodsInfoByCodeOrName(item)
                    if not goods[0]:
                        return Result.illegal(goods[1])
                    goods = goods[1]
                    stock = FaKuyouGoodsStock.objects.filter(
                        Q(goods_id=goods['id']) & Q(stores_id=store.id)).first()
                    # 构建盘点单详情对象
                    inventory_info = {"purchase_code": inventory['purchase_code'], "purchase_time": purchase_time,
                                      "goods_type": goods['goods_type_id'], "goods_id": goods['id'],
                                      "stores_id": store.id, "goods_attr": goods['more_attribute'],
                                      "stock": stock.stock, "invertory_stock": item['number'],
                                      "profit": int(float(item['number']) - float(stock.stock)),
                                      "admin_id": requestData['user_id']}
                    if inventory_info['profit'] > 0:
                        check_profit += inventory_info['profit']
                    else:
                        check_loss += inventory_info['profit']
                    inventory_info_serializer = FaKuyouInventoryInfoSerializer(data=inventory_info)
                    inventory_info_serializer.is_valid(raise_exception=True)
                    inventory_info_serializer.save()
                    inventory_info = {"purchase_code": inventory['purchase_code'], "goods_name": goods['goods_name'],
                                      "store_name": store.name, "stock": stock.stock, "invertory_stock": item['number'],
                                      "profit": inventory_info['profit']}

                    inventory_info_list.append(inventory_info)
                    inventory['result'] = ""
                if check_profit > 0:
                    inventory['result'] += f"盘盈：{check_profit}; "
                if check_loss < 0:
                    inventory['result'] += f"盘亏：{check_loss};"

                inventory_serializer = FaKuyouInventorySerializer(data=inventory)
                inventory_serializer.is_valid(raise_exception=True)
                inventory_serializer.save()
            return Result.success("生成盘点单成功",
                                  {"盘点单": inventory_serializer.data, "盘点详情单": inventory_info_list})
        except Exception as e:
            return Result.error(str(e))

    # 生成其他入库单
    @transaction.atomic()
    def addWarehouse(self, request):
        try:
            with transaction.atomic():
                # 获取请求信息
                requestData = setDictNone(request.data)
                purchase_time = int(time.time())
                purchase_code = getOrderCode(17)
                # 查询供应商
                supplier = FaKuyouSuppliers.objects.filter(supplyer_name=requestData.get('supplier')).first()
                warehouse = {"admin_id": requestData['user_id'], "purchase_code": purchase_code,
                             "purchase_time": purchase_time, "business_type": 2, "order_id": 0}
                if supplier:
                    warehouse["suppliers_id"] = supplier.id
                warehouse = updateOrderExamineStatus(warehouse, requestData)
                # 构建入库详情单对象
                warehouse_info_list = []
                all_number = 0
                all_price = 0
                for item in requestData['items']:
                    goods = getGoodsInfoByCodeOrName(item)
                    if not goods[0]:
                        return Result.illegal(goods[1])
                    goods = goods[1]
                    # 获取仓库对象
                    if item.get('store'):
                        store = FaKuyouStores.objects.filter(name=item.get('store')).first()
                    else:
                        store = FaKuyouStores.objects.filter(id=goods['manager_warehouse_id']).first()
                    stock = FaKuyouGoodsStock.objects.filter(Q(goods_id=goods['id']) & Q(stores_id=store.id)).first()

                    warehouse_info = {"admin_id": requestData['user_id'], "purchase_code": purchase_code,
                                      "purchase_time": purchase_time, "goods_id": goods['id'],
                                      "goods_attr": goods['more_attribute'], "goods_unit": goods['unit_id'],
                                      "number": item['number'], "stores_id": store.id, "stock": stock.stock,
                                      "basic_nmber": item['number'], "unit_price": item.get('price', 0),
                                      "price": int(item['number']) * int(item.get('price', 0))}
                    all_number += int(warehouse_info['number'])
                    all_price += int(warehouse_info['price'])
                    warehouse_info_serializer = FaKuyouWarehousingInfoSerializer(data=warehouse_info)
                    warehouse_info_serializer.is_valid(raise_exception=True)
                    warehouse_info_serializer.save()
                    warehouse_info = {"purchase_code": purchase_code, "purchase_time": purchase_time,
                                      "goods_name": goods['goods_name'], "goods_code": goods['goods_code'],
                                      "number": item['number'], "store_name": store.name, "stock": stock.stock,
                                      "price": warehouse_info['price']}
                    warehouse_info_list.append(warehouse_info)
                warehouse['number'] = all_number
                warehouse['price'] = all_price
                warehouse_serializer = FaKuyouWarehousingSerializer(data=warehouse)
                warehouse_serializer.is_valid(raise_exception=True)
                warehouse_serializer.save()
                warehouse = {"purchase_code": purchase_code, "purchase_time": purchase_time,
                             "number": all_number, "price": all_price}
                if supplier:
                    warehouse['supplier'] = supplier.supplyer_name
                return Result.success("生成入库单成功",
                                      {"入库单": warehouse, "入库详情单": warehouse_info_list})

        except Exception as e:
            return Result.error(str(e))

    # 生成其他出库单
    @transaction.atomic()
    def addOutWarehouse(self, request):
        try:
            with transaction.atomic():
                # 获取请求信息
                requestData = setDictNone(request.data)
                purchase_time = int(time.time())
                purchase_code = getOrderCode(18)
                # 查询供应商
                warehouse = {"admin_id": requestData['user_id'], "purchase_code": purchase_code,
                             "purchase_time": purchase_time, "business_type": 2, "order_id": 0}
                customer = FaKuyouCustomer.objects.filter(customer_name=requestData.get('customer')).first()
                if customer:
                    warehouse["customers_id"] = customer.id
                warehouse = updateOrderExamineStatus(warehouse, requestData)
                # 构建入库详情单对象
                warehouse_info_list = []
                all_number = 0
                all_price = 0
                for item in requestData['items']:
                    goods = getGoodsInfoByCodeOrName(item)
                    if not goods[0]:
                        return Result.illegal(goods[1])
                    goods = goods[1]
                    # 获取仓库对象
                    if item.get('store'):
                        store = FaKuyouStores.objects.filter(name=item.get('store')).first()
                    else:
                        store = FaKuyouStores.objects.filter(id=goods['manager_warehouse_id']).first()
                    stock = FaKuyouGoodsStock.objects.filter(Q(goods_id=goods['id']) & Q(stores_id=store.id)).first()
                    warehouse_info = {"admin_id": requestData['user_id'], "purchase_code": purchase_code,
                                      "purchase_time": purchase_time, "goods_id": goods['id'],
                                      "goods_attr": goods['more_attribute'], "goods_unit": goods['unit_id'],
                                      "number": item['number'], "stores_id": store.id, "stock": stock.stock,
                                      "basic_nmber": item['number'], "unit_price": item.get('price', 0),
                                      "price": int(item['number']) * int(item.get('price', 0))}
                    all_number += int(warehouse_info['number'])
                    all_price += int(warehouse_info['price'])
                    warehouse_info_serializer = FaKuyouWarehouseInfoSerializer(data=warehouse_info)
                    warehouse_info_serializer.is_valid(raise_exception=True)
                    warehouse_info_serializer.save()
                    warehouse_info = {"purchase_code": purchase_code, "purchase_time": purchase_time,
                                      "goods_name": goods['goods_name'], "goods_code": goods['goods_code'],
                                      "number": item['number'], "store_name": store.name, "stock": stock.stock,
                                      "price": warehouse_info['price']}
                    warehouse_info_list.append(warehouse_info)
                warehouse['number'] = all_number
                warehouse['price'] = all_price
                warehouse_serializer = FaKuyouWarehouseSerializer(data=warehouse)
                warehouse_serializer.is_valid(raise_exception=True)
                warehouse_serializer.save()
                warehouse = {"purchase_code": purchase_code, "purchase_time": purchase_time,
                             "number": all_number, "price": all_price}
                if customer:
                    warehouse['customer'] = customer.customer_name
                return Result.success("生成出库单成功",
                                      {"出库单": warehouse, "出库详情单": warehouse_info_list})

        except Exception as e:
            return Result.error(str(e))

    # 组装单
    @transaction.atomic()
    def addAssemble(self, request):
        try:
            with transaction.atomic():
                # 获取请求信息
                requestData = setDictNone(request.data)
                purchase_time = int(time.time())
                assemble_temp = FaKuyouAssembleTemp.objects.filter(
                    purchase_code=requestData.get("temp_code", None)).first()
                # 获取单号报错，需要在本地获取单号。
                purchase_code = getOrderCode(19)
                if assemble_temp:

                    assemble = {"admin_id": requestData.get("user_id"), "purchase_code": purchase_code,
                                "purchase_time": purchase_time, "business_type": 1, "money": requestData.get("money")}
                    assemble = updateOrderExamineStatus(assemble, requestData)
                    assemble_serializer = FaKuyouAssembleSerializer(data=assemble)
                    assemble_serializer.is_valid(raise_exception=True)
                    assemble_serializer.save()
                    assemble_temp_info = FaKuyouAssembleInfoTemp.objects.filter(purchase_id=assemble_temp.id)
                    assemble_temp_info_serializer = FaKuyouAssembleInfoTempSerializer(assemble_temp_info, many=True)
                    assemble_info_list = assemble_temp_info_serializer.data
                    assemble_info_serializer = FaKuyouAssembleInfoSerializer(data=assemble_info_list, many=True)
                    assemble_info_serializer.is_valid(raise_exception=True)
                    assemble_info_serializer.save()

                else:
                    # 查询组装商品信息
                    assemble_goods = requestData.get('assemble')
                    goods = getGoodsInfoByCodeOrName(assemble_goods)
                    if not goods[0]:
                        return Result.illegal("组装商品不存在")
                    assemble = {"admin_id": requestData.get('user_id'), "purchase_code": purchase_code,
                                "purchase_time": purchase_time, "business_type": 1,
                                "money": requestData.get("money", None)}
                    assemble = updateOrderExamineStatus(assemble, requestData)
                    assemble_serializer = FaKuyouAssembleSerializer(data=assemble)
                    assemble_serializer.is_valid(raise_exception=True)
                    assemble_serializer.save()
                    assemble_info = {}
                    assemble_info.update(assemble)
                    status, stock_number, store_id = getGoodsStockInfoByCodeOrName(assemble_goods)
                    if not status:
                        return Result.illegal("仓库不存在")
                    assemble_info['stores_id'] = store_id
                    assemble_info['allow_stock'] = stock_number
                    assemble_info['type'] = 1
                    assemble_info['number'] = assemble_goods.get('number')
                    assemble_info['basic_number'] = assemble_goods.get('number')
                    assemble_info['unit_cost'] = assemble_goods.get('price')
                    assemble_info['goods_id'] = goods[1]['id']
                    assemble_info['goods_unit'] = goods[1]['unit_id']
                    assemble_info['goods_attr'] = goods[1]['more_attribute']
                    assemble_info['goods_name'] = goods[1]['goods_name']
                    assemble_info['goods_code'] = goods[1]['goods_code']
                    assemble_info_serializer = FaKuyouAssembleInfoSerializer(data=assemble_info)
                    assemble_info_serializer.is_valid(raise_exception=True)
                    assemble_info_serializer.save()
                    assemble_info_list = [assemble_info_serializer.data]
                    for item in requestData.get('items'):
                        goods = getGoodsInfoByCodeOrName(item)
                        if not goods:
                            return Result.illegal("商品不存在")
                        status, stock_number, store_id = getGoodsStockInfoByCodeOrName(item)
                        if not status:
                            return Result.illegal("仓库不存在")
                        assemble_info = {}
                        assemble_info.update(assemble)
                        assemble_info.update(goods[1])
                        assemble_info['stores_id'] = store_id
                        assemble_info['type'] = 2
                        assemble_info['allow_stock'] = stock_number
                        assemble_info['number'] = item.get('number')
                        assemble_info['basic_number'] = item.get('number')
                        assemble_info['unit_cost'] = item.get('price')
                        assemble_info['goods_id'] = goods[1]['id']
                        assemble_info['goods_unit'] = goods[1]['unit_id']
                        assemble_info_serializer = FaKuyouAssembleInfoSerializer(data=assemble_info)
                        assemble_info_serializer.is_valid(raise_exception=True)
                        assemble_info_serializer.save()
                        assemble_info_list.append(assemble_info_serializer.data)
                return Result.success("生成组装单成功",
                                      {"组装单": assemble_serializer.data,
                                       "组装详情单": assemble_info_list})
        except Exception as e:
            return Result.error(str(e))

    # 拆卸单
    @transaction.atomic()
    def addSplit(self, request):
        try:
            with transaction.atomic():
                # 获取请求信息
                requestData = setDictNone(request.data)
                purchase_time = int(time.time())
                assemble_temp = FaKuyouSplitTemp.objects.filter(
                    purchase_code=requestData.get("temp_code", None)).first()
                # 获取单号报错，需要在本地获取单号。
                purchase_code = getOrderCode(20)
                if assemble_temp:

                    assemble = {"admin_id": requestData.get("user_id"), "purchase_code": purchase_code,
                                "purchase_time": purchase_time, "business_type": 1, "money": requestData.get("money")}
                    assemble = updateOrderExamineStatus(assemble, requestData)
                    assemble_serializer = FaKuyouSplitSerializer(data=assemble)
                    assemble_serializer.is_valid(raise_exception=True)
                    assemble_serializer.save()
                    assemble_temp_info = FaKuyouSplitInfoTemp.objects.filter(purchase_id=assemble_temp.id)
                    assemble_temp_info_serializer = FaKuyouSplitInfoTempSerializer(assemble_temp_info, many=True)
                    assemble_info_list = assemble_temp_info_serializer.data
                    assemble_info_serializer = FaKuyouSplitInfoSerializer(data=assemble_info_list, many=True)
                    assemble_info_serializer.is_valid(raise_exception=True)
                    assemble_info_serializer.save()

                else:
                    # 查询组装商品信息
                    assemble_goods = requestData.get('assemble')
                    goods = getGoodsInfoByCodeOrName(assemble_goods)
                    if not goods[0]:
                        return Result.illegal("组装商品不存在")
                    assemble = {"admin_id": requestData.get('user_id'), "purchase_code": purchase_code,
                                "purchase_time": purchase_time, "business_type": 1,
                                "money": requestData.get("money", None)}
                    assemble = updateOrderExamineStatus(assemble, requestData)
                    assemble_serializer = FaKuyouSplitSerializer(data=assemble)
                    assemble_serializer.is_valid(raise_exception=True)
                    assemble_serializer.save()
                    assemble_info = {}
                    assemble_info.update(assemble)
                    status, stock_number, store_id = getGoodsStockInfoByCodeOrName(assemble_goods)
                    if not status:
                        return Result.illegal("仓库不存在")
                    assemble_info['stores_id'] = store_id
                    assemble_info['allow_stock'] = stock_number
                    assemble_info['type'] = 1
                    assemble_info['number'] = assemble_goods.get('number')
                    assemble_info['basic_number'] = assemble_goods.get('number')
                    assemble_info['unit_cost'] = assemble_goods.get('price')
                    assemble_info['goods_id'] = goods[1]['id']
                    assemble_info['goods_unit'] = goods[1]['unit_id']
                    assemble_info['goods_attr'] = goods[1]['more_attribute']
                    assemble_info['goods_name'] = goods[1]['goods_name']
                    assemble_info['goods_code'] = goods[1]['goods_code']
                    assemble_info_serializer = FaKuyouSplitInfoSerializer(data=assemble_info)
                    assemble_info_serializer.is_valid(raise_exception=True)
                    assemble_info_serializer.save()
                    assemble_info_list = [assemble_info_serializer.data]
                    for item in requestData.get('items'):
                        goods = getGoodsInfoByCodeOrName(item)
                        if not goods:
                            return Result.illegal("商品不存在")
                        status, stock_number, store_id = getGoodsStockInfoByCodeOrName(item)
                        if not status:
                            return Result.illegal("仓库不存在")
                        assemble_info = {}
                        assemble_info.update(assemble)
                        assemble_info.update(goods[1])
                        assemble_info['stores_id'] = store_id
                        assemble_info['type'] = 2
                        assemble_info['allow_stock'] = stock_number
                        assemble_info['number'] = item.get('number')
                        assemble_info['basic_number'] = item.get('number')
                        assemble_info['unit_cost'] = item.get('price')
                        assemble_info['goods_id'] = goods[1]['id']
                        assemble_info['goods_unit'] = goods[1]['unit_id']
                        assemble_info_serializer = FaKuyouSplitInfoSerializer(data=assemble_info)
                        assemble_info_serializer.is_valid(raise_exception=True)
                        assemble_info_serializer.save()
                        assemble_info_list.append(assemble_info_serializer.data)
                return Result.success("生成拆卸单成功",
                                      {"拆卸单": assemble_serializer.data,
                                       "拆卸详情单": assemble_info_list})
        except Exception as e:
            return Result.error(str(e))


# 执行sql语句
class TableSqlView(ViewSet):
    def getCreatTableSql(self, request):
        table_list = request.data['table_list']
        print("------------------------------获取的表名------------------------------\n" + table_list.__str__())
        try:
            with connection.cursor() as cursor:
                data = {}
                for table in table_list:
                    sql = f"SHOW CREATE TABLE {table};"
                    cursor.execute(sql)
                    rows = cursor.fetchall()
                    if rows:
                        # 过滤无关字段
                        rows = filter_create_table_sql(rows[0][1], rows[0][0])
                        data[table] = rows
            return Result.success("查询成功", data)
        except Exception as e:
            return Result.error("查询失败", str(e))

    @transaction.atomic()
    def executeSql(self, request):
        sql_list = request.data['sql_list']
        print("------------------------------执行的sql语句------------------------------\n" + sql_list.__str__())
        data = {}
        j = 0

        try:
            with transaction.atomic():
                with connection.cursor() as cursor:
                    for i in sql_list:
                        cursor.execute(i)
                        if cursor.description:
                            rows = cursor.fetchall()
                            if rows:
                                # 获取表头
                                com_list = [desc[0] for desc in cursor.description]
                                result = filter_data(i, rows, com_list)
                                if isinstance(result, tuple) and len(result) == 2:
                                    rows, indexes_to_remove = result
                                else:
                                    rows = result
                                    indexes_to_remove = []  # 默认值
                                for i in indexes_to_remove:
                                    del com_list[i]
                                # 创建外层数组添加表头
                                list_data = [com_list]
                                for row in rows:
                                    # 创建存储数据的数组
                                    list_data.append(list(row))
                                key = 'data' + j.__str__()
                                data[key] = list_data
                                j += 1
                    data = handleForeignKey(data)
                    print(data)
                    return Result.success("执行成功", data)


        except Exception as e:
            print(
                "\033[0;31;40m------------------------------执行的sql语句失败------------------------------\033[0m\n" + f'sql语句错误：{e}')
            return Result.illegal("执行失败", str(e))
        finally:
            # 关闭游标和连接
            if cursor:
                cursor.close()
            if connection:
                connection.close()


# 生成excel表格
class GetExcel(ViewSet):

    @transaction.atomic()
    def getExcel(self, request):
        try:
            with transaction.atomic():
                # 生成excel文件
                file_name = request.data['file_name']
                md = request.data['md']
                status, file_path = getExcelByMarkdown(md, file_name)
                if status:
                    return Result.success("excel文件创建成功", {'file_path': file_path})
                return Result.illegal("excel文件创建失败，请重试。", file_path)

        except Exception as e:
            return Result.error("生成excel文件失败", str(e))
